import { SMSCaptchFetch } from "@/services/login";
import type { ButtonProps } from "antd";
import { Button } from "antd";
import React, { FC, forwardRef, useEffect, useState } from "react";

interface SMSCaptchaProps {
  phone: string;
  countDown?: number;
  buttonProps?: ButtonProps;
  getRandomKey?: (key?: string) => void;
}

const SMSCaptcha: FC<SMSCaptchaProps> = forwardRef((props, ref: any) => {
  const { countDown, phone, buttonProps } = props;

  const [count, setCount] = useState<number>(countDown || 60);
  const [timing, setTiming] = useState(false);
  const [loading, setLoading] = useState<boolean>();

  useEffect(() => {
    let interval: number = 0;
    const { countDown } = props;
    if (timing) {
      interval = window.setInterval(() => {
        setCount((preSecond) => {
          if (preSecond <= 1) {
            setTiming(false);
            clearInterval(interval);
            // 重置秒数
            return countDown || 60;
          }
          return preSecond - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [timing]);

  const handleClick = () => {
    setLoading(true);

    SMSCaptchFetch()
      .then((res) => {
        setTiming(true);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  return (
    <Button
      style={{
        display: "block",
      }}
      disabled={timing || !phone}
      loading={loading}
      {...buttonProps}
      onClick={handleClick}
    >
      {timing ? `${count} 秒后重新获取` : "获取验证码"}
    </Button>
  );
});

SMSCaptcha.defaultProps = {
  countDown: 60,
};

export default SMSCaptcha;
